package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorsMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.vo.DishVO;
import net.bytebuddy.implementation.bytecode.Throw;
import org.aspectj.bridge.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.sky.service.DishService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service

public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    FlavorsMapper flavorsMapper;
    @Autowired
    SetMealDishMapper setMealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void saveWithFlavors(DishDTO dishDTO) {

        //先执行菜品的sql，那么就只需要拿dish表就好
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.save(dish);
        //新增菜品分为2步:口味添加，菜品信息和口味分开sql执行
        Long id = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() != 0) {
            //遍历flavors，逐个加上
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });
            flavorsMapper.save(flavors);//插入到flavors中

            //删除缓存
            //获取对应的key
            cleanCache("dish_"+dishDTO.getCategoryId());


        }

        //数据库的多条语句插入

    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //分页查询菜品
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());//交给PageHelper自动limit
        //然后再正常的查询所有菜品
        Page<DishVO> query = dishMapper.pageQuery(dishPageQueryDTO);
        long total = query.getTotal();
        List<DishVO> queryResult = query.getResult();
        return new PageResult(total, queryResult);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO geyByidWithFlavor(Long id) {
        //查询菜品基本信息还有口味信息两条sql！！！
        Dish dish = dishMapper.getByDishId(id);

        List<DishFlavor> dishFlavor = flavorsMapper.getDishId(id);//根据菜品id查询出来的是一个口味集合

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    @Override
    public void updateWithFlavors(DishDTO dishDTO) {
        //菜品信息修改以及口味的修改
        //1、菜品基础信息修改
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);

        //先删除掉原有的口味，再根据所传添加上
        //1、删除口味根据菜品ID
        flavorsMapper.delete(dishDTO.getId());
        //添加口味
        List<DishFlavor> flavors = dishDTO.getFlavors();//获得所有菜品的口味，再逐个添加
        if (flavors!=null && flavors.size()!=0 ){
            flavors.forEach(flavor ->{
                flavor.setDishId(dishDTO.getId());
            });
            flavorsMapper.save(flavors);
        }

        cleanCache("dish_*");

//        flavorsMapper.save(dishDTO.getFlavors());
    }

    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //菜品的批量删除，同时需要判断是否关联有套餐以及是否起售状态和口味，关联套餐和起售状态则不能删除，口味则要一并删掉
        //判断是否关联套餐，先根据id查询
        for (Long id : ids) {
            Dish bId = dishMapper.getByDishId(id);
            if(bId.getStatus()== StatusConstant.ENABLE){
                //起售状态，则不删，直接调用异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        List<Long> dishID = setMealDishMapper.selDish(ids);
        if (dishID.size()!=0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //如果都没关联，则可以开始删除操作,口味则要一并删掉, 事务处理器
        for (Long id : ids) {
            dishMapper.delete(id);
            //根据每个dish_id删除口味
            flavorsMapper.delete(id);
        }
        cleanCache("dish_*");
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorsMapper.getDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<DishVO> dishList(Long id) {
        //根据分类id查询相关菜品
        Dish dish=new Dish();
        dish.setCategoryId(id);
        List<Dish> dishList = dishMapper.list(dish);//菜品集合
        List<DishVO> voList=new ArrayList<>();
        for (Dish dish1 : dishList) {
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(dish1,dishVO);
            voList.add(dishVO);
        }


        return voList;
    }

    //统一清楚缓存方法
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
